package com.my.study.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author yidujun
 * @date 2022/8/4 14:16
 */
@Slf4j
public final class ReqRespUtils {
    
    private ReqRespUtils() {}

    public static void writeResp(HttpServletResponse response, Object value) {
        writeResp(response, value, false);
    }
    
    public static void writeResp(HttpServletResponse response, Object value, boolean close) {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            if (value instanceof String) {
                writer.write(((String) value));
            } else {
                writer.write(JsonUtils.obj2String(value));       
            }
            writer.flush();
        } catch (Exception e) {
            log.error("write response error.", e);
        } finally {
            if (close && null != writer) {
                writer.close();
            }
        }
    }
}
